﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using Business;

public partial class client_Client : System.Web.UI.Page {
    String clientname,clientid;
    bool reporttype = false;
    string[] siteselected;
    string[] componentIDs2;
    string[] componentIDs;
    string surveydate;
    bool oldreport_cb;
    int i;
    protected void Page_Load(object sender, EventArgs e) {
        i = 0;
        componentIDs2 = new string[100];
       
       // reporttype = (bool)Session["OilReport"];
        clientname = (String)Session["clientName"];
        clientid = (String)Session["clientid"];
        // reporttype = (bool)Session["OilReport"];//true: oil report;false:vibration report
        siteselected = (String[])Session["sitename"];
        surveydate = (string)Session["SurveyDate"];
        int size = siteselected.Length;
        if (!IsPostBack)
        {
     
            Generate_TreeView();
           
            
     
        }
     
        componentIDs = new string[i];
        for (int j = 0; j < i;j++ )

        {
            componentIDs[j] = componentIDs2[j];
        }
        Session["componentIDS"] = componentIDs;
        if (!reporttype)
        {
            report_content.Attributes["src"] = "Welcome.aspx";
        }
        else
        {
            report_content.Attributes["src"] = "OilReport_Mangage.aspx";
        }
   
        // string s = siteselected[1];


    }
    protected void Generate_TreeView() {
                    CreateConn objcon;

        try
        {
           
             

            TreeNode rootnode;

            // Add the Root Client
            rootnode = new TreeNode(clientname);
            rootnode.SelectAction = TreeNodeSelectAction.SelectExpand;
            rootnode.NavigateUrl = "Welcome.aspx";
            rootnode.Target = "report_content";

            tree1.Nodes.Add(rootnode);
            foreach (string sitename in siteselected)
            {
                TreeNode secnode = new TreeNode(sitename);
                rootnode.ChildNodes.Add(secnode);
                String getsitename = sitename;
                objcon = new CreateConn();
                string query = "SELECT m.machine_id, m.machineName FROM Machines AS m INNER JOIN Sites AS s ON m.site_id = s.site_id WHERE s.siteName ='"+sitename+"'";
                secnode.SelectAction = TreeNodeSelectAction.SelectExpand;
                if (objcon == null)
                {
                    objcon = new CreateConn();
                }
                DataTable dt = objcon.SQLConnDataTable(query);
               

                int resultcount = dt.Rows.Count;
                if (dt.Rows.Count > 0)
                {
                    int rowscount = dt.Rows.Count;
                    foreach (DataRow r in dt.Rows)
                    {
                        TreeNode thirdnode = new TreeNode(r["machineName"].ToString());
                        string machineid = r["machine_id"].ToString();
                        string machinename = r["machineName"].ToString();
                        thirdnode.ImageUrl = GetIcon(machineid);
                        secnode.ChildNodes.Add(thirdnode);
                        string query2 = "SELECT component_id,componentName from Components where machine_id ='"+machineid+"'";
                 //       if(objcon==null){
                            objcon = new CreateConn();

                      //  }
                        DataTable component_dt =  objcon.SQLConnDataTable(query2);
                        bool lastcomponent = false;
                        foreach (DataRow r2 in component_dt.Rows)
                        {
                            string compname = r2["componentName"].ToString();
                            string componentid = r2["component_id"].ToString();
                            componentIDs2[i] = componentid;
                            i++;

                            TreeNode fourthnode = new TreeNode(r2["componentName"].ToString());
                            thirdnode.ChildNodes.Add(fourthnode);
                            if (r2 == component_dt.Rows[component_dt.Rows.Count - 1])
                            {
                                lastcomponent = true;
                            }
                       
                                if (oldreport_cb)
                                {
                                    Comment cmt = new Comment();
                                    cmt.copyOldReport(Int32.Parse(componentid), surveydate);
                                }
                             
                                fourthnode.NavigateUrl = "Newreport.aspx?machinename=" + machinename + "&componentname=" + compname +
                                    "&componentID=" + componentid + "&lastcomponent=" + lastcomponent + "&machineid=" + machineid + "&IsModifyReport=true" + "&ReportDate=" + surveydate;

                            
                            fourthnode.Target = "report_content";
                        
                //            report_content.Attributes["src"] = "Newreport.aspx?machinename="+machinename+"&componentname="+compname;

                        }
                    }
                }
            }

        }
        catch (Exception e)
        {
            // e.Message;
            String errmsg = e.ToString();
        }
        finally
        {
            
        }   
    
    
    }
 /*   protected void Generate_TreeView() {
        try {
            CreateConn objcon = new CreateConn();
           // string client_query = "select clientName, c.client_id AS client from Clients c, Users u"
           // + " where u.client_id = c.client_id And u.username = '"
           // + Session["username"].ToString() + "'";
           // DataTable dt = objcon.SQLConnDataTable(client_query);
            TreeNode node;
            
            // Add the Root Client
            node = new TreeNode(clientname);
            node.SelectAction = TreeNodeSelectAction.SelectExpand;
            node.NavigateUrl = "Welcome.aspx";
            node.Target = "report_content";

            tree1.Nodes.Add(node);

            // find the subclient
            objcon = new CreateConn();
            string query1 = "select clientName from Clients c where c.parent_client_id = " +clientname;
            DataTable dt1 = objcon.SQLConnDataTable(query1);
            

            if (dt1.Rows.Count > 0) {

                // Add the subclient in main client
                TreeNode man = new TreeNode();
                for (int j = 0; j < tree1.Nodes.Count; j++) {
                    man = tree1.Nodes[j];

                    foreach (DataRow dr in dt1.Rows) {
                        TreeNode node1 = new TreeNode(dr["clientName"].ToString());
                        node1.SelectAction = TreeNodeSelectAction.SelectExpand;
                        node1.NavigateUrl = "#";
                        man.ChildNodes.Add(node1);
                    }
                }

                TreeNode thirdnode = new TreeNode();
                for (int k = 0; k < man.ChildNodes.Count; k++) {
                    thirdnode = man.ChildNodes[k];
                    objcon = new CreateConn();
                    string query_site = "select siteName from Sites s, Clients c where c.client_id = s.client_id and c.clientName='" + thirdnode.Text + "'";
                    DataTable dt_sites = objcon.SQLConnDataTable(query_site);

                    foreach (DataRow dr in dt_sites.Rows) {
                        TreeNode node1 = new TreeNode(sitename);
                        node1.SelectAction = TreeNodeSelectAction.SelectExpand;
                        node1.NavigateUrl = "#";
                        thirdnode.ChildNodes.Add(node1);
                        thirdnode.CollapseAll();
                    }

                    for (int l = 0; l < thirdnode.ChildNodes.Count; l++) {
                        TreeNode fourthnode = thirdnode.ChildNodes[l];
                        String siteName = fourthnode.Text;
                        objcon = new CreateConn();
                        string query2 = "select machineName, machine_id, client_id from Machines m, Sites s where s.site_id = m.site_id AND m.status = 'Activated' and s.siteName='" + fourthnode.Text + "'";
                        DataTable dt2 = objcon.SQLConnDataTable(query2);

                        foreach (DataRow dr in dt2.Rows) {
                            String machinename = dr["machineName"].ToString();
                            String machineid = dr["machine_id"].ToString();
                            String client_id = dr["client_id"].ToString();
                            TreeNode node1 = new TreeNode(dr["machineName"].ToString());
                            node1.SelectAction = TreeNodeSelectAction.SelectExpand;
                            node1.NavigateUrl = "Vibration_Report.aspx?id=" + machineid + "&client_id =" + client_id;
                            node1.Target = "report_content";
                            fourthnode.ChildNodes.Add(node1);
                            fourthnode.CollapseAll();
                        }
                    }
                }
            } else {
                TreeNode thirdnode = new TreeNode();
                for (int k = 0; k < tree1.Nodes.Count; k++) {
                    thirdnode = tree1.Nodes[k];
                    objcon = new CreateConn();
                    string query_site = "select siteName from Sites s, Clients c where c.client_id = s.client_id and c.clientName='" + thirdnode.Text + "'";
                    DataTable dt_sites = objcon.SQLConnDataTable(query_site);

                    foreach (DataRow dr in dt_sites.Rows) {
                        TreeNode node1 = new TreeNode(dr["siteName"].ToString());
                        node1.SelectAction = TreeNodeSelectAction.SelectExpand;
                        node1.NavigateUrl = "#";
                        thirdnode.ChildNodes.Add(node1);
                        thirdnode.CollapseAll();
                    }

                    for (int l = 0; l < thirdnode.ChildNodes.Count; l++) {
                        TreeNode fourthnode = thirdnode.ChildNodes[l];
                        String siteName = fourthnode.Text;
                        objcon = new CreateConn();
                        string query2 = "select machineName, machine_id, client_id from Machines m, Sites s where s.site_id = m.site_id AND m.status = 'Activated' and s.siteName='" + fourthnode.Text + "'";
                        DataTable dt2 = objcon.SQLConnDataTable(query2);

                        foreach (DataRow dr in dt2.Rows) {
                            String machinename = dr["machineName"].ToString();
                            String machineid = dr["machine_id"].ToString();
                            String client_id = dr["client_id"].ToString();
                            TreeNode node1 = new TreeNode(dr["machineName"].ToString());
                            node1.SelectAction = TreeNodeSelectAction.SelectExpand;
                            node1.NavigateUrl = "Vibration_Report.aspx?id=" + machineid + "&client_id=" + client_id;
                            node1.ImageUrl = GetIcon(machineid);
                            node1.Target = "report_content";
                            fourthnode.ChildNodes.Add(node1);
                            fourthnode.CollapseAll();
                        }
                    }
                }
            }
        } catch (Exception err) {
            Console.Write("Err msg:" + err.Message);
        }
    }*/

    protected string StatusToIcon(string statusID) {
        string src = "";
        //if (statusID.Contains("4")) {
        //    src = "../images/machine_red.png";
        //} else if (statusID.Contains("3")) {
        //    src = "../images/machine_orange.png";
        //} else if (statusID.Contains("2")) {
        //    src = "../images/machine_yellow.png";
        //} else {
        //    src = "../images/machine_green.png";
        
        //}
        if (statusID.Equals("4"))
        {
            src = "../images/machine_red.png";
        }
        else if (statusID.Equals("3"))
        {
            src = "../images/machine_orange.png";
        }
        else if (statusID.Equals("2"))
        {
            src = "../images/machine_yellow.png";
        }
        else
        {
            src = "../images/machine_green.png";

        }
        return src;
    }

    protected string GetIcon(string machineID) {
        string src = String.Empty;
        string query = "SELECT   MAX(status_id) AS status_id"
+" FROM      ComponentStatus"
+" WHERE   (component_id IN"
                    +" (SELECT   component_id"
                    + " FROM      Components"
                    + " WHERE   (machine_id = '"+machineID+"'))) AND (dateRecorded IN"
                    +" (SELECT   MAX(dateRecorded) AS dateRecorded"
                    +" FROM      ComponentStatus AS ComponentStatus_1"
                    +" WHERE   (component_id in (select component_id From Components WHERE machine_id='"+machineID+"'))))";
        CreateConn objcon = new CreateConn();
        DataTable dt = objcon.SQLConnDataTable(query);
        foreach(DataRow dr in dt.Rows){
            string statusID = dr["status_id"].ToString();
            src = StatusToIcon(statusID);
        }
        //try {
        //    CreateConn objcon = new CreateConn();
        //    string queryDate = "SELECT MAX(ComponentStatus.dateEntered) AS dateEntered, COUNT(*) AS totalNumber" +
        //        " FROM Components INNER JOIN" +
        //        " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
        //        " WHERE (Components.machine_id = '" + machineID + "')";
        //    DataTable dt = new DataTable();
        //    dt = objcon.SQLConnDataTable(queryDate);
        //    string dateEntered = dt.Rows[0]["dateEntered"].ToString();

        //    objcon = new CreateConn();
        //    string component_query = "SELECT ComponentStatus.status_id" +
        //        " FROM Components INNER JOIN" +
        //        " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
        //        " WHERE (Components.machine_id = '" + machineID + "') AND (ComponentStatus.dateEntered = CONVERT(datetime, '" + dateEntered + "', 103))";
        //    DataTable component_dt = objcon.SQLConnDataTable(component_query);
        //    int count = Convert.ToInt32(dt.Rows[0]["totalNumber"].ToString());

        //    string[] statusID = new string[count];
        //    for (int i = 0; i < count; i++) {
        //        try {
        //            string test = component_dt.Rows[i]["status_id"].ToString();
        //            statusID[i] = component_dt.Rows[i]["status_id"].ToString();
        //        } catch (Exception err) {
        //            Console.Write("Err msg:" + err.Message);
        //        }
        //    }
      
        //    src = GetOilIconByStatusID(statusID);
        //} catch (Exception err) {
        //    Console.Write("Err msg:" + err.Message);
        //}
        return src;
    }

    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e) {
        Session.Abandon();
        Session.Contents.RemoveAll();
        FormsAuthentication.SignOut();
    }

}
